<?php

namespace App\Http\Controllers\Api\Promotion;

use Illuminate\Http\Request;

use Carbon\Carbon;

use App\Http\Controllers\Controller;

use App\Models\Promotion\Seckill;

use Illuminate\Support\Facades\Redis as Redis;

use App\Models\ConfigureFunction; //功能配置表

use App\Models\Promotion\SeckillGoods;

use App\Models\Mall\MallMaster;

use App\Models\Promotion\PromotionBuyLog;

use App\Models\Goods\GoodsStore;

use App\Models\Goods\GoodsSale;

use App\Models\Customer\Customer;

class SeckillCartController extends Controller
{

    //秒杀加入购物车
    public function add(Request $request){

        $session_id = $request->input('session_id', session_id());
        $promotion_id = $request->input('id');
        $time_slot_id = $request->input('tsid');
        $postID = $request->input('postID');
        $mallID = $request->input('mallID', 1);
        $goods_amount = $request->input('goods_amount');
        $platform = $request->input('platform', 6);

        if (empty($session_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
        }

        if (!ebsig_is_int($promotion_id)) {
            return response()->json(['code' => 10001, 'message' => '缺少参数：id']);
        }

        if (!ebsig_is_int($time_slot_id)) {
            return response()->json(['code' => 10002, 'message' => '缺少参数：tsid']);
        }

        if (!ebsig_is_int($postID)) {
            return response()->json(['code' => 10003, 'message' => '缺少参数：psotID']);
        }

        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');
        if ($is_open_choose_mall == 1) {
            if (!ebsig_is_int($mallID)) {
                return response()->json(['code' => 10004, 'message' => '请先选择门店']);
            }

            //查询门店信息
            $mall = MallMaster::where(['mallID' => $mallID])->first();
            if (!$mall) {
                return response()->json(['code' => 10005, 'message' => '门店信息不存在']);
            }
        }

        if (!ebsig_is_int($goods_amount)) {
            $goods_amount = 1;
        }

        //获取会员ID信息
        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 10006, 'message' => '请登录']);
        }

        //查询秒杀活动
        $seckill_promotion = Seckill::getCache($promotion_id);
        if (!$seckill_promotion) {
            return response()->json(['code' => 10007, 'message' => '秒杀活动没有找到']);
        }

        if ( $seckill_promotion['start_date'] > date('Y-m-d') ) {
            return response()->json(['code' => 10008, 'message' => '秒杀活动未开始']);
        }

        if ( $seckill_promotion['end_date'] < date('Y-m-d') ) {
            return response()->json(['code' => 10009, 'message' => '秒杀活动已结束']);
        }

        //查询秒杀时间段
        $seckill_time = $seckill_promotion['goods'][$time_slot_id];
        if (!$seckill_time) {
            return response()->json(['code' => 100010, 'message' => '秒杀活动不存在']);
        }

        if ( $seckill_time['startTime'] > date('H:i:s') ) {
            return response()->json(['code' => 100011, 'message' => '秒杀未开始']);
        }

        if ( $seckill_time['endTime'] < date('H:i:s') ) {
            return response()->json(['code' => 100012, 'message' => '秒杀已结束']);
        }

        //查询秒杀商品
        $seckill_goods = $seckill_promotion['goods'][$time_slot_id]['list'][$postID];
        if (!$seckill_goods) {
            return response()->json(['code' => 100013, 'message' => '秒杀商品没有找到']);
        }

        //秒杀已购数量
        $saled_amount = Redis::get('SEC_KILL_BUY_NUM_' . $promotion_id . '_' . $time_slot_id . '_' . $postID);
        if ($seckill_goods['max_sale_amount'] < $saled_amount + 1 ) {
            return response()->json(['code' => 100014, 'message' => '库存不足']);
        }

        //检查会员最大购买数量
        $buy_lod_data = PromotionBuyLog::where([
            'promotion_id' => $promotion_id,
            'promotion_extend_id' => $time_slot_id,
            'pcustID' => $pcustID,
            'postID' => $postID
        ])->first();
        if (!$buy_lod_data) {
            $promotionBuyLog = new PromotionBuyLog();
            $promotionBuyLog->uuid = makeUuid();
            $promotionBuyLog->timeStamp = Carbon::now();
            $promotionBuyLog->creator = 'system';
            $promotionBuyLog->createTime = Carbon::now();
            $promotionBuyLog->promotion_id = $promotion_id;
            $promotionBuyLog->promotion_extend_id = $time_slot_id;
            $promotionBuyLog->pcustID = $pcustID;
            $promotionBuyLog->postID = $postID;
            $promotionBuyLog->buy_num = 0;
            $promotionBuyLog->max_buy_num = $seckill_goods['limit_count'];
            $promotionBuyLog->save();
        } else {
            $buy_lod_data = $buy_lod_data->toArray();
            if ($seckill_goods['limit_count'] != $buy_lod_data['max_buy_num']) {
                PromotionBuyLog::where([
                    'promotion_id' => $promotion_id,
                    'promotion_extend_id' => $time_slot_id,
                    'pcustID' => $pcustID,
                    'postID' => $postID
                ])->update(['max_buy_num' => $seckill_goods['limit_count']]);
            }

            if ($buy_lod_data['max_buy_num'] > 0 && $buy_lod_data['buy_num'] + $goods_amount > $buy_lod_data['max_buy_num']) {
                return response()->json(['code' => 100015, 'message' => '超过会员最大购买个数']);
            }

        }

        //查询商品基本信息
        $goods_data = GoodsSale::getCache($postID, $mallID);
        if ( !$goods_data || $goods_data['useFlg'] != 1 ) {
            return response()->json(['code' => 100016, 'message' => '商品不存在或已下架']);
        }

        $store = GoodsStore::search($goods_data['product_code'], $goods_data['product_spec'], $mallID);
        if ($store < $goods_amount) {
            return response()->json(['code' => 100017, 'message' => '商品库存不足']);
        }

        //查询会员信息
        $cust_data = Customer::find($pcustID);
        if (!$cust_data) {
            return response()->json(['code' => 1000018, 'message' => '会员信息不存在']);
        }

        //结算配置，获取配送运费
        $bill_config = $seckill_promotion['config'];
        $freight_free = 0;
        if ( $bill_config ) {
            $freight_free = $bill_config['freight_free'];
        }

        $host = $request->getSchemeAndHttpHost();
        $goods_data['goods_amount'] = $goods_amount;
        $goods_data['salePrice'] = $seckill_goods['salePrice'];
        $goods_data['price'] = $seckill_goods['kill_price'];
        $goods_data['img_link'] = $host . $seckill_goods['seckill_img'];
        $goods_data['wap_link'] = '';
        $goods_data['goods_groupID'] = $promotion_id;
        $goods_data['time_slot_id'] = $seckill_goods['time_slot_id'];

        //保存购物车数组
        $bill_data = array(
            'bill_status' => 0,
            'freight_free' => $freight_free,
            'ziti' => 1,
            'sendTypeID' => 2,
            'custID' => $cust_data['custID'],
            'cardNo' => $cust_data['cardNo'],
            'mallID' => $mallID,
            'mallCode' => isset($mall['mallCode']) ? $mall['mallCode'] : '',
            'mallName' => isset($mall['mallName']) ? $mall['mallName'] : '',
            'bill_totalMoney' => $seckill_goods['kill_price'],
            'bill_totalPaid' => $seckill_goods['kill_price'],
            'bill_totalPoints' => 0,
            'bill_pointsPrice' => 0,
            'bill_subtract_money' => 0,
            'bill_points_money' => 0,
            'bill_balance_money' => 0,
            'bill_coupon_money' => 0,
            'bill_card_money' => 0,
            'bill_payable' => $seckill_goods['kill_price'],
            'bill_total_amount' => $goods_amount,
            //订单类型；1、正常订单 2、特价购订单 3、闪购订单 4、积分订单 5、补货单 6、换货单 7、众筹单 8、预售订单 9、团购订单 10、虚拟商品订单 12、秒杀订单
            'billType' => 12,
            'remark' => null,
            'payPwd' => null,
            'payment_method_id' => null,
            'send_region_id' => 0,
            //订单配置
            'bill_config_id' => $seckill_promotion['config']['config_id'],
            'change_time' => null,
            //订单商品
            'goods' => array(
               $this->createCartGoods($goods_data)
            ),
            'activity_id' => $promotion_id,
            'pay' => []
        );

        Redis::setex('G_SEC_KILL_' .  $pcustID, 360000, json_encode($bill_data,true));

        return response()->json(['code' => 200, 'message' => 'ok']);
    }

    //处理秒杀商品数组
    private function createCartGoods($goods_array){

        if (strstr($goods_array['spec'], '-默认')) {
            $goods_array['spec'] = '';
        }

        return array (
            'mainPostID' => $goods_array['mainPostID'],
            'goodsID' => $goods_array['goodsID'],
            'postID' => $goods_array['postID'],
            'goodsName' => $goods_array['goodsName'],
            'spec' => $goods_array['spec'],
            'goods_amount' => $goods_array['goods_amount'],
            'salePrice' => $goods_array['salePrice'],
            'price' => $goods_array['price'],
            'recordPrice' => $goods_array['recordPrice'],
            'addPoints' => 0,
            'salePoints' => 0,
            'goodsWeight' => $goods_array['goodsWeight'],
            'goodsRate'=>$goods_array['goodsRate'],
            'goods_from' => 12,
            'goods_groupID' => $goods_array['goods_groupID'],
            'goods_status' => 1,
            'pic' => $goods_array['img_link'],
            'wap_link' => $goods_array['wap_link'],
            'product_code' => $goods_array['product_code'],
            'product_spec' => $goods_array['product_spec'],
            'marketPrice' => $goods_array['marketPrice'],
            'supplier_id' => $goods_array['supplier_id'],
            'promotion' => null,
            'promotion_id' => 0,
            'goods_remark' => '',
            'goodsType' => isset($goods_array['goodsType'])?$goods_array['goodsType']:1,
            'virtual_id' => isset($goods_array['virtual_id'])?$goods_array['virtual_id']:0,
            'virtual_name' =>  isset($goods_array['virtual_name'])?$goods_array['virtual_name']:'',
            'virtual_type' =>  isset($goods_array['virtual_type'])?$goods_array['virtual_type']:1,
            'time_slot_id' =>  isset($goods_array['time_slot_id'])?$goods_array['time_slot_id']:0,
        );
    }

}